package com.example.zhish.asynctask_demo001;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class ImageTest extends AppCompatActivity {

    private ImageView imageView;
    private ProgressBar progressBar;
    private static String url ="http://img.my.csdn.net/uploads/201504/12/1428806103_9476.png";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_test);

        imageView = (ImageView) findViewById(R.id.image1);
        progressBar = (ProgressBar) findViewById(R.id.pro1);

        //设置传递进去的参数
        new MyasyncTask1().execute(url);

    }

    class MyasyncTask1 extends AsyncTask<String,Void,Bitmap>{

        @Override
        protected Bitmap doInBackground(String... params) {
            //实现步骤：
            //通过param[0]获取传递进来的参数

            String url = params[0];
            Bitmap bitmap = null;
            URLConnection urlConnection;
            InputStream is;
            try {
                urlConnection = new URL(url).openConnection();
                is = urlConnection.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is);
                //通过decodeStream解析输入流
                bitmap = BitmapFactory.decodeStream(bis);
                is.close();
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            //将bitmap作为返回值
            return bitmap;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            progressBar.setVisibility(View.GONE);
            imageView.setImageBitmap(bitmap);
        }
    }
}
